package org.example.myleet.p463;

class Solution {

    private static int[][] directions = new int[][]{{0,-1},{1,0},{0,1},{-1,0}};

    public int islandPerimeter(int[][] grid) {
        int perimeter = 0;
        int h = grid.length;
        int w = grid[0].length;
        for (int y=0; y<grid.length; y++) {
            for (int x=0; x<grid[y].length; x++) {
                if (grid[y][x] == 1) {
                    //地面
                    perimeter += calculatePositionPerimeter(grid, y, x, h, w);
                }
            }
        }
        return perimeter;
    }

    private int calculatePositionPerimeter(int[][] grid, int y, int x, int h, int w) {
        int p = 4;
        int ny, nx;
        for (int[] direction : directions) {
            ny = y+direction[0];
            nx = x+direction[1];
            if ((ny>=0) && (ny<h) && (nx>=0) && (nx<w)) {
                //保证某方向临近点在地图内
                if (grid[ny][nx] == 1) {
                    //某方向临近点也是地面，则本位置(x,y)的周长-1
                    --p;
                }
            }
        }
        return p;
    }
}
